package com.qdxwx.web.controller.user;

import com.qdxwx.common.config.UploadConfig;
import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.page.PageRequest;
import com.qdxwx.common.upload.UploadUtils;
import com.qdxwx.common.utils.*;
import com.qdxwx.data.service.approal.ApproalService;
import com.qdxwx.data.service.category.CategoryService;
import com.qdxwx.data.service.document.DocumentService;
import com.qdxwx.data.service.member.MemberTypeService;
import com.qdxwx.data.service.user.UserCountService;
import com.qdxwx.models.approal.Approal;
import com.qdxwx.models.category.Category;
import com.qdxwx.models.document.Document;
import com.qdxwx.models.document.DocumentDetail;
import com.qdxwx.models.document.DocumentQuery;
import com.qdxwx.models.enums.DocumentType;
import com.qdxwx.models.enums.ModuleType;
import com.qdxwx.models.member.MemberType;
import com.qdxwx.models.user.User;
import com.qdxwx.models.user.UserCount;
import com.qdxwx.web.controller.BaseController;
import com.qdxwx.web.utils.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/user/document")
public class UserDocumentController extends BaseController {

    @Autowired
    private DocumentService documentService;
    @Autowired
    private MemberTypeService memberTypeService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ApproalService approalService;
    @Autowired
    private UserCountService userCountService;

    //资料列表
    @RequestMapping("/list.html")
    public String list(HttpServletRequest request, ModelMap mmap) {
        long userId = LoginUser.getUserId(request);
        if (userId < 1) {
            return "redirect:/auth/login.html";
        }
        int status = TKConvert.toInteger(request.getParameter("status"), 0);
        int currentPage = TKConvert.toInteger(request.getParameter("page"), 1);
        int limit = TKConvert.toInteger(request.getParameter("limit"), 10);
        PageRequest page = new PageRequest(currentPage, limit);
        DocumentQuery query = new DocumentQuery();
        query.setStatus(status);
        query.setUserId(userId);
        List<Document> documentList = documentService.getList(query, page);
        int total = documentService.count(query);
        query.setStatus(0);
        int notCount = documentService.count(query);
        query.setStatus(1);
        int pastCount = documentService.count(query);
        query.setStatus(-1);
        int refuseCount = documentService.count(query);
        mmap.put("notCount", notCount);
        mmap.put("pastCount", pastCount);
        mmap.put("refuseCount", refuseCount);
        mmap.put("status", status);
        mmap.put("documentList", documentList);
        mmap.put("totalPages", page.getTotalPages(total));
        mmap.put("page", page);
        mmap.put("user", LoginUser.getUser(request));
        if (TKRequest.isMobileBrowse(request)) {
            return getViewPathH5("user/uc-document-list");
        }
        return getViewPath("ucenter/uc-document-list");
    }

    //编辑资料
    @RequestMapping("/add.html")
    public String add(HttpServletRequest request, ModelMap mmap) {
        User user = LoginUser.getUser(request);
        if (user == null) {
            return "redirect:/auth/login.html";
        }
        MemberType memberType = new MemberType();
        memberType.setStatus(0);
        List<MemberType> members = memberTypeService.getList(memberType,null);
        DocumentQuery query = new DocumentQuery();
        query.setUserId(user.getUserId());
        query.setStatus(0);
        int notCount = documentService.count(query);
        query.setStatus(1);
        int pastCount = documentService.count(query);
        query.setStatus(-1);
        int refuseCount = documentService.count(query);
        mmap.put("notCount", notCount);
        mmap.put("pastCount", pastCount);
        mmap.put("refuseCount", refuseCount);
        mmap.put("documentTypes", DocumentType.values());
        mmap.put("members", members);
        mmap.put("user", user);
        return getViewPath("ucenter/uc-document-add");
    }

    //添加保存资料
    @PostMapping("/add.json")
    @ResponseBody
    public AjaxResult add(HttpServletRequest request) {
        User user = LoginUser.getUser(request);
        if (user == null) return AjaxResult.error("登录超时");
        int categoryId = TKConvert.toInteger(request.getParameter("categoryId"));
        if (categoryId < 1) return AjaxResult.error("请选择类别");
        Category category = categoryService.get(categoryId);
        if (category == null) return AjaxResult.error("类别categoryId有误");
        String fileUrl = TKString.trim(request.getParameter("fileUrl"));
        if (TKString.isEmpty(fileUrl)) return AjaxResult.error("请输入文件地址或上传");
        String title = TKString.trim(request.getParameter("title"));
        if (TKString.isEmpty(title)) return AjaxResult.error("请输入文件名");
        String cover = TKString.trim(request.getParameter("cover"));
        if (TKString.isEmpty(cover)) return AjaxResult.error("请输入封面地址或上传");
        String intro = TKString.trim(request.getParameter("intro"));
        if (TKString.isEmpty(intro)) return AjaxResult.error("请输入资料简介");
        DocumentDetail document = new DocumentDetail();
        document.setCompanyId(user.getCompanyId());
        document.setChannelId(11);
        document.setCategoryId(category.getCategoryId());
        document.setCategoryName(category.getCategoryName());
        document.setSubjectId(category.getSubjectId());
        document.setTypeId(TKConvert.toInteger(request.getParameter("typeId")));
        document.setTitle(title);
        document.setTags(TKString.trim(request.getParameter("tags")));
        document.setCover(cover);
        document.setIntro(intro);
        document.setFileUrl(fileUrl);
        document.setFileExt(UploadUtils.getFileExt(fileUrl));
        document.setFileSize(TKConvert.toLong(request.getParameter("fileSize")));
        document.setUserId(user.getUserId());
        document.setUserName(user.getUserName());
        document.setPrice(TKConvert.toInteger(request.getParameter("price")) * 100);
        document.setLevelId(TKConvert.toInteger(request.getParameter("levelId")));
        document.setStatus(0);
        //判断图片有没有修改
        if (!TKString.isEmpty(document.getCover())) {
            //原图
            String oldPath = document.getCover();
            //新图
            if (oldPath.contains("/temps/")) {
                String newPath = String.format("%s/%s", UploadConfig.uploadCoverThumb, oldPath.substring(oldPath.indexOf("/temps/") + 7));
                ImageUtils.zoomWithCut(UploadConfig.uploadRoot + oldPath, UploadConfig.uploadRoot + newPath, 400, 280);
                document.setCover(newPath);
            }
        }
        int row = documentService.insert(document);
        if (row > 0) {
            UserCount userCount = new UserCount();
            userCount.setId(user.getUserId());
            userCount.setDocumentUploadDay(1);
            userCountService.append(userCount);
        }
        return row > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    //编辑资料
    @GetMapping("/edit.html")
    public String edit(HttpServletRequest request, ModelMap mmap) {
        User user = LoginUser.getUser(request);
        if (user == null) {
            return "redirect:/auth/login.html";
        }
        int id = TKConvert.toInteger(request.getParameter("id"));
        if (id < 1) return toErrorView(request,"参数错误");
        Document document = documentService.get(id);
        if (document == null) return toErrorView(request,"找不到指定资料");
        if (document.getUserId() != user.getUserId()) return toErrorView(request,"非法操作");
        if (document.getStatus() == 1) return toErrorView(request,"审核通过资料不可修改");
        MemberType memberType = new MemberType();
        memberType.setStatus(0);
        List<MemberType> members = memberTypeService.getList(memberType,null);
        DocumentQuery query = new DocumentQuery();
        query.setUserId(user.getUserId());
        query.setStatus(0);
        int notCount = documentService.count(query);
        query.setStatus(1);
        int pastCount = documentService.count(query);
        query.setStatus(-1);
        int refuseCount = documentService.count(query);
        mmap.put("notCount", notCount);
        mmap.put("pastCount", pastCount);
        mmap.put("refuseCount", refuseCount);
        mmap.put("document", document);
        mmap.put("documentTypes", DocumentType.values());
        mmap.put("members", members);
        mmap.put("user", user);
        return getViewPath("ucenter/uc-document-edit");
    }

    //编辑保存资料
    @PostMapping("/edit.json")
    @ResponseBody
    public AjaxResult edit(HttpServletRequest request) {
        User user = LoginUser.getUser(request);
        if(user == null) return AjaxResult.error("登录超时");
        int id = TKConvert.toInteger(request.getParameter("id"));
        if (id < 1) return AjaxResult.error("缺少参数id");
        DocumentDetail document = documentService.get(id);
        if (document == null) return AjaxResult.error("找不到指定id的资料");
        if (document.getUserId() != user.getUserId()) return AjaxResult.error("非法操作");
        if (document.getStatus() == 1) return AjaxResult.error("审核通过资料不可修改");
        int categoryId = TKConvert.toInteger(request.getParameter("categoryId"));
        if (categoryId < 1) return AjaxResult.error("请选择类别");
        Category category = categoryService.get(categoryId);
        if (category == null) return AjaxResult.error("类别categoryId有误");
        String fileUrl = TKString.trim(request.getParameter("fileUrl"));
        if (TKString.isEmpty(fileUrl)) return AjaxResult.error("请输入文件地址或上传");
        String title = TKString.trim(request.getParameter("title"));
        if (TKString.isEmpty(title)) return AjaxResult.error("请输入文件名");
        String cover = TKString.trim(request.getParameter("cover"));
        if (TKString.isEmpty(cover)) return AjaxResult.error("请输入封面地址或上传");
        String intro = TKString.trim(request.getParameter("intro"));
        if (TKString.isEmpty(intro)) return AjaxResult.error("请输入资料简介");
        document.setTypeId(TKConvert.toInteger(request.getParameter("typeId")));
        document.setCategoryId(category.getCategoryId());
        document.setCategoryName(category.getCategoryName());
        document.setSubjectId(category.getSubjectId());
        document.setFileUrl(fileUrl);
        document.setFileExt(UploadUtils.getFileExt(fileUrl));
        document.setFileSize(TKConvert.toLong(request.getParameter("fileSize")));
        document.setTitle(title);
        document.setCover(cover);
        document.setIntro(intro);
        document.setTags(TKString.trim(request.getParameter("tags")));
        document.setPrice(TKConvert.toInteger(request.getParameter("price")) * 100);
        document.setLevelId(TKConvert.toInteger(request.getParameter("levelId")));
        document.setStatus(0);
        //判断图片有没有修改
        if (!TKString.isEmpty(document.getCover())) {
            //原图
            String oldPath = document.getCover();
            //新图
            if (oldPath.contains("/temps/")) {
                String newPath = String.format("%s/%s", UploadConfig.uploadCoverThumb, oldPath.substring(oldPath.indexOf("/temps/") + 7));
                ImageUtils.zoomWithCut(UploadConfig.uploadRoot + oldPath, UploadConfig.uploadRoot + newPath, 400, 280);
                document.setCover(newPath);
            }
        }
        return AjaxResult.success(documentService.update(document));
    }

    //删除资料操作
    @PostMapping("/remove.json")
    @ResponseBody
    public AjaxResult remove(HttpServletRequest request) {
        User user = LoginUser.getUser(request);
        if(user == null) return AjaxResult.error("登录超时");
        int id = TKConvert.toInteger(request.getParameter("id"));
        DocumentDetail document = documentService.get(id);
        if (document == null) return AjaxResult.error("未找到指定id资料，id=" + id);
        if (document.getUserId() != user.getUserId()) return AjaxResult.error("非法操作");
        if (document.getStatus().equals(1)) return AjaxResult.error("审核通过资料不能删除");
        int row = documentService.delete(document.getId());
        if (row > 0) {
            //删除审核关联表
            approalService.deleteByInfoId(document.getId(), ModuleType.DOCUMENT.ordinal());
            //同步删除文件
            FileUtils.deleteFile(UploadConfig.uploadRoot + document.getCover());
            FileUtils.deleteFile(UploadConfig.uploadRoot + document.getFileUrl());
        }
        return AjaxResult.success(row);
    }

    //资料评语
    @GetMapping("/comment.html")
    public String comment(HttpServletRequest request, ModelMap mmap){
        User user = LoginUser.getUser(request);
        if (user == null) {
            return "redirect:/auth/login.html";
        }
        int id = TKConvert.toInteger(request.getParameter("id"));
        if (id < 1) return toErrorView(request,"参数错误");
        Document document = documentService.get(id);
        if (document == null) return toErrorView(request,"找不到指定资料");
        if (document.getUserId() != user.getUserId()) return toErrorView(request,"非法操作");
        Approal approal = new Approal();
        approal.setInfoId(document.getId());
        approal.setTypeId(ModuleType.DOCUMENT.ordinal());
        List<Approal> approalList = approalService.getList(approal, null);
        mmap.put("approalList",approalList);
        return getViewPath("ucenter/uc-document-comment");
    }
}
